package com.py.sale.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.py.api.PyCodeApi;
import com.py.sale.domain.PyAttachment;
import com.py.sale.domain.SysUser;
import com.py.sale.message.MessageProducer;
import com.py.sale.service.IPyAttachmentService;
import com.py.sale.service.SaleInfoService;
import com.py.sale.service.WhInventoryVoService;
import com.py.sale.service.impl.PyAttachmentServiceImpl;
import com.py.sale.vo.WhInventoryVo;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.py.sale.domain.OdSale;
import com.py.sale.service.IOdSaleService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 销售Controller
 * 
 * @author 童佳
 * @date 2024-12-03
 */
@RestController
@RequestMapping("/sale")
public class OdSaleController extends BaseController
{
    @Autowired
    private IOdSaleService odSaleService;

    @Resource
    private WhInventoryVoService whInventoryVoService;
    @Resource
    private IPyAttachmentService pyAttachmentService;

    @Resource
    private SaleInfoService saleInfoService;


    @Resource
    private PyCodeApi pyCodeApi;

    @Resource
    private MessageProducer messageProducer;

    /**
     * 获取编码
     */
    @PostMapping("/getcode")
    public Map<String, Object> getCode(@RequestParam(value = "code",required = false) Integer code){
        System.out.println("进来了"+code);
        return pyCodeApi.generateCode(code);
    }

    /**
     * 查询销售列表
     */
    @RequiresPermissions("sale:sale:list")
    @GetMapping("/list")
    public TableDataInfo list(OdSale odSale)
    {
        startPage();
        List<OdSale> list = odSaleService.selectOdSaleList(odSale);
        return getDataTable(list);
    }

    /**
     * 导出销售列表
     */
    @RequiresPermissions("sale:sale:export")
    @Log(title = "销售", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OdSale odSale)
    {
        List<OdSale> list = odSaleService.selectOdSaleList(odSale);
        ExcelUtil<OdSale> util = new ExcelUtil<OdSale>(OdSale.class);
        util.exportExcel(response, list, "销售数据");
    }

    /**
     * 获取销售详细信息
     */
    @RequiresPermissions("sale:sale:query")
    @GetMapping(value = "/{saleId}")
    public AjaxResult getInfo(@PathVariable("saleId") Integer saleId)
    {
        System.out.println("saleId："+saleId);
        return success(odSaleService.selectOdSaleBySaleId(saleId));
    }

    /**
     * 新增销售
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("sale:sale:add")
    @Log(title = "销售", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OdSale odSale)
    {
        System.out.println("odSale："+odSale);
        System.out.println("number:"+odSale.getNumber());
        System.out.println("codeId:"+odSale.getCodeId());
        pyCodeApi.saveCode(odSale.getCodeId(),odSale.getNumber());
        odSale.setCreateBy(SecurityUtils.getUsername());
        SysUser sysUser =odSaleService.selectBySysUserName(SecurityUtils.getUsername());
        odSale.setCreateDept(sysUser.getDeptName());
        odSale.setCreateTime(DateUtils.getNowDate());
        odSale.setIsDel("0");
        System.out.println("OdSale ："+odSale);
        List<Object> fileList = odSale.getFileList();
        if(fileList.size()>0){
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    Object ob=fileMap.get("size");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            String name = (String) data.get("name");
                            String url = (String) data.get("url");
                            System.out.println("Name: " + name);
                            System.out.println("URL: " + url);
                            PyAttachment pyAttachment=new PyAttachment();
                            pyAttachment.setBusinessType("销售单");
                            pyAttachment.setOwnershipNumber(odSale.getSaleCode());
                            pyAttachment.setFileName(name);
                            pyAttachment.setSize(Long.parseLong(ob.toString()));
                            pyAttachment.setFilePath(url);
                            pyAttachmentService.insertPyAttachment(pyAttachment);
                        }
                    }
                }
            }
        }
        messageProducer.sendMessageDirect("新增了一个销售单: "+odSale.getSaleCode()+" 待审核!");
        return toAjax(odSaleService.insertOdSale(odSale));
    }

    /**
     * 修改销售
     */
    @RequiresPermissions("sale:sale:edit")
    @Log(title = "销售", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OdSale odSale)
    {
        odSale.setUpdateBy(SecurityUtils.getUsername());
        odSale.setUpdateTime(new Date());
        pyAttachmentService.deletePyAttachmentByOwnershipNumber(odSale.getSaleCode());
        List<Object> fileList = odSale.getFileList();
        if (fileList.size() > 0) {
            System.out.println("进来了11111111111111");
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    String name = (String) fileMap.get("name");
                    String url = (String) fileMap.get("url");
                    Object size = fileMap.get("size");

                    // 如果 name 和 url 不为空，直接使用
                    if (name != null && url != null) {
                        System.out.println("Name: " + name);
                        System.out.println("URL: " + url);
                        PyAttachment pyAttachment = new PyAttachment();
                        pyAttachment.setBusinessType("销售单");
                        pyAttachment.setOwnershipNumber(odSale.getSaleCode());
                        pyAttachment.setFileName(name);
                        pyAttachment.setSize(Long.parseLong(size.toString()));
                        pyAttachment.setFilePath(url);
                        pyAttachmentService.insertPyAttachment(pyAttachment);
                        continue;
                    }

                    // 如果 name 或 url 为空，尝试从 response 中获取
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            name = (String) data.get("name");
                            url = (String) data.get("url");
                            if (name != null && url != null) {
                                System.out.println("Name: " + name);
                                System.out.println("URL: " + url);
                                PyAttachment pyAttachment = new PyAttachment();
                                pyAttachment.setBusinessType("销售单");
                                pyAttachment.setOwnershipNumber(odSale.getSaleCode());
                                pyAttachment.setFileName(name);
                                pyAttachment.setSize(Long.parseLong(size.toString()));
                                pyAttachment.setFilePath(url);
                                pyAttachmentService.insertPyAttachment(pyAttachment);
                            }
                        }
                    }
                }
            }
        }
        return toAjax(odSaleService.updateOdSale(odSale));
    }

    /**
     * 删除销售
     */
    @RequiresPermissions("sale:sale:remove")
    @Log(title = "销售", businessType = BusinessType.DELETE)
	@DeleteMapping("/{saleIds}")
    public AjaxResult remove(@PathVariable Integer[] saleIds)
    {
        return toAjax(odSaleService.deleteOdSaleBySaleIds(saleIds));
    }

    /**
     * 查询所有货品信息
     */
    @RequestMapping("/selectAllSaleProduct")
    public TableDataInfo selectAllSaleProduct(WhInventoryVo whInventoryVo){
        System.out.println("进来近似数:"+whInventoryVo);
        startPage();
        List<WhInventoryVo> list =whInventoryVoService.selectWhInventoryVoList(whInventoryVo);
        list.forEach(System.out::println);
        return getDataTable(list);
    }

    //审核
    @RequiresPermissions("sale:sale:check")
    @RequestMapping("/check")
    public AjaxResult check(@RequestBody Map<String,Object> map){
        System.out.println("审核的phIds:"+map);
        Map<String,Object> map1=new HashMap<>();
        map1.put("reviewer", SecurityUtils.getUsername());
        map1.put("reviewer_time",new Date());
        if((String)map.get("comments")!=null){
            map1.put("reviewer_report",map.get("comments").toString());
        }
        map1.put("sale_state",map.get("result").toString());
        List<Integer> list= (List<Integer>) map.get("phId");
        list.forEach(System.out::println);
        map1.put("sale_id",list);
        return toAjax(odSaleService.checkById(map1));
    }

    @RequiresPermissions("sale:sale:revoke")
    @RequestMapping("/revoke")
    public AjaxResult revoke(@RequestParam("saleId") Integer saleId){
        System.out.println("撤回的phid:"+saleId);
        return toAjax(odSaleService.revokeById(saleId));
    }

    @RequestMapping("/fileInfo")
    public Map<String,Object> fileInfo(@RequestParam("salecode") String salecode){
        Map<String,Object> map=new HashMap<>();
        PyAttachment pyAttachment=new PyAttachment();
        pyAttachment.setOwnershipNumber(salecode);
        map.put("fileList",pyAttachmentService.selectPyAttachmentList(pyAttachment));
        map.put("orderInfo",saleInfoService.selcteProductInfoResult(salecode));
        return map;
    }

    @RequiresPermissions("sale:sale:close")
    @RequestMapping("/colseById")
    public AjaxResult colseById(@RequestParam("saleId") Integer saleId ){
        return toAjax(odSaleService.colseById(saleId));
    }

    @RequestMapping("/findSale")
    public TableDataInfo findSale(@RequestBody OdSale odSale)
    {
        System.out.println("销售退货单中的销售单："+odSale);
        startPage();
        List<OdSale> list = odSaleService.selectOdSaleOrderByInRejected(odSale);
        return getDataTable(list);
    }

    @RequestMapping("/selectBySaleCode")
    public Map<String,Object> selectBySaleCode(@RequestParam("SaleCode") String SaleCode){
        System.out.println("selectBySaleCode:"+SaleCode);
        return odSaleService.selectBySaleCode(SaleCode);
    }
}
